package com.lmh.graphdisease.utils.ACKMPTree;

/**
 * @author lmh
 * @desc 过滤、替换工具
 * @date 2023/3/20
 */
public class ACFilter {
    private ACTree acTree;

    public ACFilter(ACTree acTree){
        this.acTree = acTree;
    }

    /**
     *@author lmh
     *@date 2023/3/20
     *@desc 过滤
     */
    public String[] filter(String words){
        if(words == null){
            return null;
        }
        String[] strs = words.split("");
        String[] result = null;
        Node curNode = acTree.getRootNode();
        Node subNode;
        String s;
        int fromPos = 0;
        for (int i = 0;i<strs.length;i++){
            s = strs[i];
            subNode = curNode.getSubNode(s);
            while (subNode == null && curNode != acTree.getRootNode()){
                curNode = curNode.getFailNodeTo();
                subNode = curNode.getSubNode(s);
            }
            if(subNode!=null){
                curNode = subNode;
            }
            if(curNode.isTerminal()){
                int pos = i - curNode.getLevel() + 1;
                if(pos < fromPos){
                    pos = fromPos;
                }
                if(result == null){
                    result = words.split("");
                }
                for (;pos<=i;pos++){
                    result[pos] = "*";
                }
                fromPos = i+1;
            }
        }
        if(result == null){
            return words.split("");
        }
        return result;
    }
 }
